import math

import torch
import torch.nn.functional as F
import NLP_LanguageModel as lm
import dltools
from torch import nn

#X, W_xh = torch.normal(0, 1, (3, 1)), torch.normal(0, 1, (1, 4))
#H, W_hh = torch.normal(0, 1, (3, 4)), torch.normal(0, 1, (4, 4))
#print(torch.matmul(X, W_xh) + torch.matmul(H, W_hh))
# 先相乘再相加 = 先拼接再相乘
#print(torch.matmul(
#    torch.cat((X, H), dim=1), torch.cat((W_xh, W_hh), dim=0))
#)

batch_size, num_steps = 32, 35
train_iter, vocab = dltools.load_data_time_machine(batch_size, num_steps=num_steps)
for x, y in train_iter:
#    print(x.shape)
#    print(y.shape)
    break

# 输入数据 one_hot 编码
#print(F.one_hot(torch.tensor([0, 2]), num_classes=len(vocab)))
X = torch.arange(10).reshape((2, 5))
#print(X)
x = F.one_hot(X.T, 28)
#print(x.shape)

def get_params(vocab_size, num_hiddens, device):
    num_inputs = num_outputs = vocab_size

    def normal(shape):
        return torch.randn(size=shape, device=device) *0.01

    # 隐藏层参数
    W_xh = normal((num_inputs, num_hiddens))
    W_hh = normal((num_hiddens, num_hiddens))
    b_h = torch.zeros(num_hiddens, device=device)

    # 输出层参数
    W_hq = normal((num_hiddens, num_outputs))
    b_q = torch.zeros(num_outputs, device=device)

    # 把这些参数都设置 requires_grad = True 也可以用nn.Parameter(W_xh)
    params = [W_xh, W_hh, b_h, W_hq, b_q]
    for param in params:
        param.requires_grad_(True)
    return params


#print(get_params(28, 512, "cuda:0"))

# 初始化时返回隐藏状态
def init_rnn_state(batch_size, num_hiddens, device):
    # 返回的是一个元组
    return (torch.zeros((batch_size, num_hiddens),device=device),)

# rnn主体结构
def rnn(inputs, state, params):
    # inputs的形状：（时间步数量，批次大小，词表大小）
    W_xh, W_hh, b_h, W_hq, b_q = params
    H, = state #只要第一个
    outputs = []
    for X in inputs:
#        print(f"X.shape:{X.shape}") [batch_size, num_inputs]
#        print(f"W_xh.shape:{W_xh.shape}") [num_inputs, num_hiddens]
#        print(f"torch.mm(X, W_xh).shape:{torch.mm(X, W_xh).shape}") [batch_size, num_hiddens]
#        print(f"H.shape:{H.shape}") [batch_size, num_hiddens]
#        print(f"W_hh.shape:{W_hh.shape}") [num_hiddens, num_hiddens]
#        print(f"torch.mm(H, W_hh).shape:{torch.mm(H, W_hh).shape}") [batch_size, num_hiddens]
#        print(f"b_h.shape:{b_h.shape}")
        H = torch.tanh(torch.mm(X, W_xh) + torch.mm(H, W_hh) + b_h)
        Y = torch.mm(H, W_hq) + b_q
        outputs.append(Y)
    return torch.cat(outputs, dim=0), (H,)

# 包装成类
class RNNModelScratch:
    def __init__(self, vocab_size, num_hiddens, device, get_params, init_state, forward_fn):
        self.vocab_size = vocab_size
        self.num_hiddens = num_hiddens
        self.params = get_params(vocab_size, num_hiddens, device)
        self.init_state, self.forward_fn = init_state, forward_fn

    def __call__(self, X, state):
        X = F.one_hot(X.T, self.vocab_size).type(torch.float32)
        return self.forward_fn(X, state, self.params)

    def begin_state(self, batch_size, device):
        return self.init_state(batch_size, self.num_hiddens, device)

device = "cuda:0" if torch.cuda.is_available() else "cpu"

num_hiddens = 512
net = RNNModelScratch(len(vocab), num_hiddens, device, get_params, init_rnn_state, rnn)
#state = net.begin_state(X.shape[0], device)
#Y, new_state = net(X.to(device), state)


def predict(prefix, num_preds, net, vocab, device):
    state = net.begin_state(batch_size=1, device=device)
    outputs = [vocab[prefix[0]]]
    get_input = lambda: torch.tensor([outputs[-1]], device=device).reshape((1, 1))
    # 预热
    for y in prefix[1:]:
        _, state = net(get_input(), state)
        outputs.append(vocab[y])

    # 真正的预测
    for i in range(num_preds):
        y, state = net(get_input(), state)
        outputs.append(int(y.argmax(dim=1).reshape(1)))

    return "".join([vocab.idx_to_token[i] for i in outputs])

print(predict("time traveller ", 10, net, vocab, device))

# 梯度裁剪
def grad_clipping(net, theta):
    params = []
    if isinstance(net, nn.Module):
        params = [p for p in net.parameters() if p.requires_grad]
    else:
        params = net.params

    norm = torch.sqrt(sum([torch.sum((p.grad ** 2)) for p in params]))
    if norm > theta:
        for param in params:
            param.grad[:] *= theta / norm


# 训练
def train_epoch(net, train_iter, loss, updater, device, use_random_iter):
    state = None
    timer = dltools.Timer()
    metric = dltools.Accumulator(2)
    # 取数据
    for X, Y in train_iter:
        if state is None or use_random_iter:
            # 第一次训练或者使用随机抽样时，都需要把state重新初始化
            state = net.begin_state(batch_size=X.shape[0], device=device)
        else:
            # 梯度释放
            if isinstance(net, nn.Module) and not isinstance(state, tuple):
                state.detach_()
            else:
                for s in state:
                    s.detach_()
        print(f"Y.shape:{Y.shape}")
        # Y.reshape只改变形状，不改变顺序。 Y.T 形状颠倒，顺序也会变
        y = Y.T.reshape(-1)
        print(f"y.shape:{y.shape}")
        X, y = X.to(device), y.to(device)
        y_hat, state = net(X, state)
        # print(f"y_hat.shape:{y_hat.shape}")
        loss_value = loss(y_hat, y.long()).mean()

        if isinstance(updater, torch.optim.Optimizer):
            updater.zero_grad()
            loss_value.backward()
            # rnn容易梯度爆炸 需要做梯度裁剪
            grad_clipping(net, 1)
            updater.step()
        else:
            loss_value.backward()
            grad_clipping(net, 1)
            updater(batch_size=1)

#        print(loss_value, y.numel())
        metric.add(loss_value * y.numel(), y.numel())
    # 返回的是困惑度 以e为底的的交叉熵损失
    return math.exp(metric[0] / metric[1]), metric[1]/ timer.stop()

def train(net, train_iter, vocab, lr, num_epochs, device, use_random_iter=False):
    loss = nn.CrossEntropyLoss()
    animator = dltools.Animator(xlabel="epoch", ylabel="perlexity", legend=["train"], xlim=[10, num_epochs])

    # 初始化
    if isinstance(net, nn.Module):
        updater = torch.optim.SGD(net.parameters(), lr)
    else:
        updater = lambda batch_size: dltools.sgd(net.params, lr, batch_size)

    pred = lambda prefix: predict(prefix, 50, net, vocab, device)
    # 训练和预测
    for epoch in range(num_epochs):
        ppl, speed = train_epoch(net, train_iter, loss, updater, device, use_random_iter)

        if (epoch + 1) % 10 == 0:
            print(pred("time traveller"))
            animator.add(epoch + 1, [ppl])
    print(f"困惑度:{ppl:.1f}, {speed:.1f}词元/秒 {str(device)}")
    print(pred("at last the time traveller"))
    print(pred("traveller"))

num_epochs = 1000
lr = 0.5
train(net, train_iter, vocab, lr, num_epochs, device)













